package models

import (
	//"errors"
	//"log"
	"time"

	"github.com/beego/beego/v2/client/orm"
	"github.com/tidwall/gjson"
)

type UserCluster struct {
	Id         int64  `json:"id"`
	Username   string `json:"username"`
	ClusterId  string `json:"clusterId"`
	Createtime string `json:"createtime"`
}

func init() {
	orm.Debug = true
	orm.RegisterModel(new(UserCluster))
}

//list
func GetUserClusterList(username, clusterId string, page int64, page_size int64) (list []UserCluster, count int64) {
	o := orm.NewOrm()
	qs := o.QueryTable(new(UserCluster))
	cond := orm.NewCondition()
	var offset int64
	if page <= 1 {
		offset = 0
	} else {
		offset = (page - 1) * page_size
	}
	if username != "" {
		cond = cond.And("username", username)
	}

	if clusterId != "" {
		cond = cond.And("cluster_id", clusterId)
	}

	qs = qs.SetCond(cond)
	qs.Limit(page_size, offset).OrderBy("-id").All(&list)
	count, _ = qs.Count()
	return list, count

}

//List
func GetUserClusterListV2(whereMap map[string]gjson.Result) (list []UserCluster, count int64) {
	o := orm.NewOrm()
	cond := orm.NewCondition()

	slb := new(UserCluster)
	qs := o.QueryTable(slb)

	var page, limit int64
	if pg, ok := whereMap["page"]; ok {
		page = pg.Int()
		delete(whereMap, "page")
	}
	if pg, ok := whereMap["limit"]; ok {
		limit = pg.Int()
		delete(whereMap, "limit")
	}
	var offset int64
	if page <= 1 {
		offset = 0
	} else {
		offset = (page - 1) * limit
	}

	for kk, vv := range whereMap {
		if vv.String() != "" {
			cond = cond.And(kk+"__contains", vv.String())
		}
	}
	qs = qs.SetCond(cond)
	qs.Limit(limit, offset).OrderBy("-id").All(&list)

	count, _ = qs.Count()
	return list, count
}

//add
func AddUserCluster(u *UserCluster) (int64, error) {
	o := orm.NewOrm()
	uc := new(UserCluster)
	uc.Username = u.Username
	uc.ClusterId = u.ClusterId
	uc.Createtime = time.Now().Format("2006-01-02 15:04:05")
	id, err := o.Insert(uc)
	return id, err
}

//del
func DelUserClusterById(Id int64) (int64, error) {
	o := orm.NewOrm()
	status, err := o.Delete(&UserCluster{Id: Id})
	return status, err
}
